/**
 * @Title: AdminController.java
 * @Package com.alex.cms.web.controllers
 * @Description: (描述该文件做什么)
 * @author Alex Lu
 * @date 2019年9月23日 下午7:16:49
 * @version V1.0
 */
package com.alex.cms.web.controllers;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alex.cms.domain.CmsArticle;
import com.alex.cms.domain.CmsCategory;
import com.alex.cms.domain.CmsChannel;
import com.alex.cms.domain.CmsSettings;
import com.alex.cms.domain.CmsSlide;
import com.alex.cms.domain.CmsUser;
import com.alex.cms.service.ICmsArticleService;
import com.alex.cms.service.ICmsCategoryService;
import com.alex.cms.service.ICmsChannelService;
import com.alex.cms.service.ICmsSettingsService;
import com.alex.cms.service.ICmsSlideService;
import com.alex.cms.service.ICmsSpecialService;
import com.alex.cms.service.ICmsUserService;
import com.alex.cms.web.constants.CMSConstants;
import com.alex.cms.web.form.ArticleForm;
import com.alex.cms.web.form.ChannelForm;
import com.alex.cms.web.vo.ArticleVo;
import com.alex.cms.web.vo.CategoryVo;
import com.alex.cms.web.vo.ResultVo;
import com.alex.cms.web.vo.SpecialVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bawei.common.Exception.CMSSystemException;
import com.bawei.common.utils.AssertionUtil;

/**
 * @ClassName: AdminController
 * @Description: (描述这个类的作用)
 * @author Alex Lu
 * @date 2019年9月23日 下午7:16:49
 *
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
	@Autowired
	private ICmsArticleService articleService;

	@Autowired
	private ICmsCategoryService categoryService;

	@Autowired
	private ICmsChannelService channelService;

	@Autowired
	private ICmsSettingsService settingsService;

	@Autowired
	private ICmsUserService userService;
	
	@Autowired
	private ICmsSlideService slideService;
	
	@Autowired
	private ICmsSpecialService specialService;

	// 跳转到后台管理的页面
	@RequestMapping("/home")
	public ModelAndView showUserSpaceView(HttpSession session) {
		ModelAndView mav = new ModelAndView("admin/home");
		return mav;
	}

	// 文章管理
	@RequestMapping("/blogs")
	public ModelAndView getCategories(@RequestParam(value = "pageNo", required = false) Integer pageNo) {
		ModelAndView mav = new ModelAndView("/admin/blog-manage");
		pageNo = pageNo != null ? pageNo : 1;
		// 指定文章列表的jsp
		// 根据用户ID获取本用户的所有文章
		QueryWrapper<ArticleVo> queryWrapper = new QueryWrapper<ArticleVo>();
		IPage<ArticleVo> articles = articleService.selectAllArticlesByUserId(new Page<ArticleVo>(pageNo, 10), queryWrapper);
		mav.addObject("blogs", articles.getRecords());
		mav.addObject("currentPage", articles.getCurrent());
		mav.addObject("pages", articles.getPages());
		return mav;
	}

	// 跳转到审核页面
	@RequestMapping("/toAudit")
	public ModelAndView auditArticleByStatus(@RequestParam("articleId") Integer articleId) {
		// 指定跳转到哪个jsp，"user-space/blog_edit"是jsp的路径
		ModelAndView mav = new ModelAndView("admin/blog_audit");
		ArticleForm articleForm = new ArticleForm();
		try {
			// 根据文章ID获取文章
			CmsArticle article = articleService.getById(articleId);
			// 断言要抛出异常，断言之后执行的语句都是正确流程
			AssertionUtil.assertFalse(article == null, CMSConstants.ARTICLE_IS_NOT_EXIST);
			articleForm.setId(articleId);
			articleForm.setTitle(article.getTitle());
			articleForm.setSummary(article.getSummary());
			articleForm.setContent(article.getContent());

			// 设置文章封面图片的值
			articleForm.setCover(article.getPicture());

			CmsCategory category = categoryService.getById(article.getCategroyId());
			category.setId(article.getCategroyId());
			articleForm.setCategory(category);
			// 返回页面数据，"blog"是前端定义的名字
			mav.addObject("blog", articleForm);
		} catch (CMSSystemException e) {
			// 视图仍然定位到文章编辑页面，错误消息在编辑页面显示
			mav.addObject("message", e.getMessage());
		}

		return mav;
	}

	// 审核
	@RequestMapping(value = "/audit")
	public ModelAndView auditArticle(@RequestParam("articleId") Integer articleId, @RequestParam("status") Integer status, HttpSession session) {
		ModelAndView mav = new ModelAndView("redirect:/admin/blogs");
		CmsArticle article = articleService.getById(articleId);
		article.setStatus(status);
		articleService.updateById(article);
		return mav;
	}

	/**
	 * 
	 * @Title: showAdminHomeView
	 * @Description: 后台首页
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/admin")
	public ModelAndView showAdminHomeView() {
		ModelAndView mav = new ModelAndView("admin/home");

		return mav;
	}

	/**
	 * 
	 * @Title: showUserManageView
	 * @Description: 用户管理
	 * @param userName
	 * @param pageSize
	 * @param pageNum
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping(value="/users",method=RequestMethod.GET)
	public ModelAndView showUserManageView(@RequestParam(required = false, value = "username") String userName, @RequestParam(required = false, value = "pageSize") Integer pageSize, @RequestParam(required = false, value = "pageNum") Integer pageNum) {
		// 指定跳转到用户管理的jsp
		ModelAndView mav = new ModelAndView("admin/user-manage");
		// 分页查询
		IPage<CmsUser> page = new Page(pageNum == null ? 1 : pageNum, pageSize == null ? 5 : pageSize);

		QueryWrapper<CmsUser> queryWrapper = new QueryWrapper<CmsUser>();
		// 根据用户名分页查询用户信息
		queryWrapper = userName != null ? queryWrapper.like("username", userName) : queryWrapper;

		page = userService.page(page, queryWrapper);
		// 返回页面数据
		mav.addObject("userPage", page);
		mav.addObject("pages", page.getPages());
		mav.addObject("currentPage",page.getCurrent());
		mav.addObject("username", userName);

		return mav;
	}

	/**
	 * 
	 * @Title: doLockUser
	 * @Description: 用户锁定
	 * @param userId
	 * @param type
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/users/lock")
	public ModelAndView doLockUser(@RequestParam("id") Integer userId, @RequestParam("type") Integer type) {
		// 指定用户管理url（重定向）
		ModelAndView mav = new ModelAndView("redirect:/admin/users");
		CmsUser user = new CmsUser();
		user.setId(userId);
		// 根据自定义的type（类型）判断是否锁定用户
		if (type != null && type == 1) {
			user.setLocked(true);
		}
		if (type != null && type == 0) {
			user.setLocked(false);
		}

		userService.saveOrUpdate(user);

		return mav;
	}
	
	@RequestMapping(value="/users",method=RequestMethod.POST)
	public ModelAndView getUserList(@RequestParam(value="username",required=false)String username,
			@RequestParam(value="pageNum",required=false)Integer pageNum){
		ModelAndView view = new ModelAndView("admin/user-manage");
		pageNum = pageNum!= null?pageNum:1;
		Page<CmsUser> page = new Page<CmsUser>(pageNum,10);
		IPage<CmsUser> pages = userService.page(page, new QueryWrapper<CmsUser>().like("username", username));
		view.addObject("userPage",pages);
		view.addObject("currentPage",pages.getCurrent());
		view.addObject("pages",pages.getPages());
		view.addObject("username",username);
		return view;
	}

	@RequestMapping("/settings")
	public ModelAndView showSettingPage() {
		ModelAndView mav = new ModelAndView("admin/settings-manage");
		List<CmsSettings> settings = settingsService.list();
		mav.addObject("settings", settings);
		return mav;
	}

	@RequestMapping("/addSetting")
	public ModelAndView showAddSettingPage() {
		ModelAndView mav = new ModelAndView("admin/settings-add");
		CmsSettings setting = new CmsSettings();
		mav.addObject("setting", setting);
		return mav;
	}

	@RequestMapping("/addSettings")
	public ModelAndView addSettingPage(CmsSettings settings) {
		ModelAndView mav = new ModelAndView("redirect:/admin/settings");
		CmsSettings setting = new CmsSettings();
		BeanUtils.copyProperties(settings, setting);
		setting.setAdminPassword(changePwdByMD5(setting.getAdminPassword(), setting.getAdminUsername(), CMSConstants.MD5_CHARACTER));
		settingsService.save(setting);
		return mav;
	}

	@RequestMapping("/editSetting")
	public ModelAndView showUpdateSettingPage(@RequestParam("settingId") Integer settingId) {
		ModelAndView mav = new ModelAndView("admin/settings-edit");
		CmsSettings setting = settingsService.getById(settingId);
		mav.addObject("setting", setting);
		return mav;
	}

	@RequestMapping("/editSettings")
	public ModelAndView editSettingPage(CmsSettings settings) {
		ModelAndView mav = new ModelAndView("redirect:/admin/settings");
		CmsSettings setting = settingsService.getById(settings.getId());
		setting.setSiteDomain(settings.getSiteDomain());
		setting.setSiteName(settings.getSiteName());
		setting.setSlideSize(settings.getSlideSize());
		setting.setArticleListSize(settings.getArticleListSize());
		setting.setAdminUsername(settings.getAdminUsername());
		if (!setting.getAdminPassword().equals(settings.getAdminPassword())) {
			setting.setAdminPassword(changePwdByMD5(setting.getAdminPassword(), setting.getAdminUsername(), CMSConstants.MD5_CHARACTER));
		}
		settingsService.updateById(setting);
		return mav;
	}
	
	@RequestMapping("/removeSetting")
	@ResponseBody
	public ResultVo removeSettingById(@RequestParam("id") Integer settingId) {
		// ajax定义的返回数据结构，所以定义这个对象的时候看ajax的data结构是什么
		ResultVo result = new ResultVo();
		// 根据配置ID删除，返回结果
		boolean removeResult = settingsService.removeById(settingId);
		// 返回结果都统一放在constants中，便于维护
		result.setStatus(removeResult ? CMSConstants.RESULT_STATUS_SUCCESS : CMSConstants.RESULT_STATUS_ERROR);
		result.setMessage(removeResult ? CMSConstants.RESULT_DELETE_MESSAGE_SUCCESS : CMSConstants.RESULT_DELETE_MESSAGE_ERROR);

		return result;
	}
	
	@RequestMapping("/resetPwd")
	public ModelAndView resetPassword(@RequestParam("settingId") Integer settingId) {
		ModelAndView mav = new ModelAndView("redirect:/admin/settings");
		CmsSettings setting = settingsService.getById(settingId);
		setting.setAdminPassword(changePwdByMD5(CMSConstants.DEFAULT_PASSWORD, setting.getAdminUsername(), CMSConstants.MD5_CHARACTER));
		settingsService.updateById(setting);
		mav.addObject("setting", setting);
		return mav;
	}
	
	@RequestMapping("/channels")
	public ModelAndView showChannels(){
		ModelAndView mav = new ModelAndView("admin/channel-manage");
		QueryWrapper<CmsChannel> queryWrapper = new QueryWrapper<CmsChannel>();
		queryWrapper = queryWrapper.orderByAsc("sorted");
		List<CmsChannel> channels = channelService.list(queryWrapper);
		List<ChannelForm>list = new ArrayList<ChannelForm>();
		for(int i=0;i<channels.size();i++){
			ChannelForm channelForm = new ChannelForm();
			BeanUtils.copyProperties(channels.get(i), channelForm);
			if(i==0){
				channelForm.setStatus(1);
			}
			if(i==channels.size()-1){
				channelForm.setStatus(0);
			}
			list.add(channelForm);
		}
		mav.addObject("channels",list);
		return mav;
	}
	
	@RequestMapping("/categories")
	public ModelAndView showCateGories(){
		ModelAndView mav = new ModelAndView("admin/category-manage");
		QueryWrapper<CategoryVo> queryWrapper = new QueryWrapper<CategoryVo>();
		queryWrapper = queryWrapper.orderByAsc("category.channel_id","category.sorted");
		List<CategoryVo> categories = categoryService.getAllCategoriesAsc(queryWrapper);
		for(int i=0;i<categories.size();i++){
			if(i==0){
				categories.get(0).setStatus(1);
				continue;
			}
			if(categories.get(i).getChannelId() != categories.get(i-1).getChannelId()){
				categories.get(i-1).setStatus(0);
				categories.get(i).setStatus(1);
			}
			if(i==categories.size()-1){
				categories.get(categories.size()-1).setStatus(0);
			}
		}
		mav.addObject("categories",categories);
		return mav;
	}
	
@RequestMapping("/slides")
public ModelAndView getSlidesList(@RequestParam(value="pageNo",required=false)Integer pageNo){
	ModelAndView mav = new ModelAndView("admin/slide-manage"); 
	pageNo = pageNo != null ?pageNo:1;
	Page<CmsSlide> page = new Page<CmsSlide>(pageNo,10);
	IPage<CmsSlide> pages = slideService.page(page);
	mav.addObject("slides",pages.getRecords());
	mav.addObject("currentPage",pages.getCurrent());
	mav.addObject("pages",pages.getPages());
	return mav;
}
/**
 * 
* @Title: getSpecialList
* @Description: 主题列表
* @return
* @return ModelAndView
 */
@RequestMapping("/specials")
public ModelAndView getSpecialList(){
	ModelAndView mav = new ModelAndView("admin/special-manage"); 
	QueryWrapper<SpecialVo> queryWrapper = new QueryWrapper<SpecialVo>();
	queryWrapper.groupBy("cs.id");
	List<SpecialVo> list = specialService.getAllSpecial(queryWrapper);
	mav.addObject("specials",list);
	return mav;
}
	/**
	 * 
	 * @Title: changePwdByMD5
	 * @Description: 用于密码加密
	 * @param password
	 *            原始密码
	 * @param userName
	 *            用户名
	 * @param MD5Content
	 *            自定义的字符串，防止被解密
	 * @return
	 * @return String 加密后的密码
	 */
	private String changePwdByMD5(String password, String userName, String MD5Content) {
		String md5Password = "";
		String pwd = password + userName + MD5Content;
		md5Password = DigestUtils.md5DigestAsHex(pwd.getBytes());
		return md5Password;
	}
}
